package com.yx.fsysserver.file.controller;

import com.alibaba.fastjson.JSON;
import com.yx.fsysserver.file.domain.VrFileInfo;
import com.yx.fsysserver.file.service.NewVrService;
import com.yx.fsysserver.file.service.VrFileInfoService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 *
 * @author lcf
 * @since 2018/7/4
 */
@RestController
@RequestMapping(value = "/newvr")
public class NewVrController {
    private Logger log = LoggerFactory.getLogger(AliOssController.class);
    @Autowired
    private NewVrService newVrService;
    @Autowired
    private VrFileInfoService vrFileInfoService;

    @Value("${vr.prefix.path}")
    private String prefixPath;
    @Autowired
    protected StringRedisTemplate incrementRedisTemplate;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public void index(long id,HttpServletRequest req, HttpServletResponse resp) throws IOException {

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out=resp.getWriter();
        out.println(this.newVrService.getIndexHtml(id,req));
    }

    @RequestMapping(value = "wxIndex", method = RequestMethod.GET)
    public void wxIndex(long id,String token,HttpServletRequest req, HttpServletResponse resp) throws IOException {

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out=resp.getWriter();

        ValueOperations<String, String> valueOperations = this.incrementRedisTemplate.opsForValue();
        String value = (String)valueOperations.get(token);
        if(StringUtils.isEmpty(value)){
            String msg="地址已失效，请重新获取！";
            out.println("<script>");
            out.println("alert('" + msg + "');");
            out.println("</script>");
        }else{
            int iValue = Integer.valueOf(value);
            System.out.println("*******************************id="+id+" token="+token+" 次数"+iValue);
            //链接使用次数减一,每次过期时间5分钟
            int nowIvalue = iValue - 1;
            if (nowIvalue == 0) {
                incrementRedisTemplate.delete(token);
            } else {
                valueOperations.set(token, String.valueOf(nowIvalue), 5L, TimeUnit.MINUTES);
            }
            out.println(this.newVrService.getIndexHtml(id, req));
        }
    }

    @RequestMapping(value = "webvrJson", method = RequestMethod.GET)
    public Map<String,Object> projectList(long id, HttpServletRequest request) {
        String serverName = request.getServerName().replace(".","");

        //获取VrFileInfo
        VrFileInfo vrFileInfo = vrFileInfoService.selectByPrimaryKey(id);
        long totalMemory = vrFileInfo.getTotalMemory();
        String prePath = prefixPath + "vr/" + vrFileInfo.getUuid() + "/";
        Map<String,Object> map = new HashMap<>();
        map.put("companyName","DefaultCompany");
        map.put("productName","BianDianZhanPC");
        map.put("dataUrl",prePath + "data.unityweb?sn="+serverName);
        map.put("asmCodeUrl",prePath + "asm.code.unityweb?sn="+serverName);
        map.put("asmMemoryUrl",prePath + "asm.memory.unityweb?sn="+serverName);
        map.put("asmFrameworkUrl",prePath + "asm.framework.unityweb?sn="+serverName);
//        map.put("asmFrameworkUrl",prePath + "http://handbook.52tsing.com/vrtest/vr1/TestWebVr.asm.framework.unityweb");
        /*map.put("dataUrl","http://localhost:88/TestWebVr/Build/TestWebVr.data.unityweb");
        map.put("asmCodeUrl","http://localhost:88/TestWebVr/Build/TestWebVr.asm.code.unityweb");
        map.put("asmMemoryUrl","http://localhost:88/TestWebVr/Build/TestWebVr.asm.memory.unityweb");
        map.put("asmFrameworkUrl","http://localhost:88/TestWebVr/Build/TestWebVr.asm.framework.unityweb");*/
        map.put("TOTAL_MEMORY",totalMemory);
        map.put("graphicsAPI",new String[]{"WebGL 2.0", "WebGL 1.0"});

        Map<String,Object> webglContextAttributes = new HashMap<>();
        webglContextAttributes.put("preserveDrawingBuffer",false);
        map.put("webglContextAttributes",webglContextAttributes);
        map.put("splashScreenStyle","Dark");
        map.put("backgroundColor","#231F20");
        return map;

    }

    @RequestMapping(value = "check", method = RequestMethod.GET)
    public String check(long Id) throws NoSuchAlgorithmException {
        //获取VrFileInfo
        VrFileInfo vrFileInfo = vrFileInfoService.selectByPrimaryKey(Id);
        String key = vrFileInfo.getSecretkey();
        String day = DateFormatUtils.format(DateUtils.addDays(new Date(),-16),"MM/dd/yyyy");
        /*MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        byte[] bytes = messageDigest.digest((key+"/"+day).getBytes());
        String sss = DigestUtils.sha1Hex("asdf");
        String result = new String(bytes);*/
        log.debug(key+day);
        log.debug(DigestUtils.sha1Hex(key+day));
        return DigestUtils.sha1Hex(key+day);
    }

    public static void main(String[] args) {
        String s = "{\"width\":50,\"height\":50}";
        System.out.println(DigestUtils.sha1Hex("74F3DB1F-4D0D-4A3B-B456-1DCFC786F80B06/05/2018"));
        String ss = StringEscapeUtils.unescapeHtml4("{&quot;width&quot;:100,&quot;height&quot;:50}");
        System.out.println(ss);
        Map<String, Object> map  = new HashMap<>();
        map.put("name","lcf");
        map.put("age",18);
        String mapStr = JSON.toJSONString(map);
        mapStr = StringEscapeUtils.escapeHtml4(mapStr);
        System.out.println(mapStr);
    }

}
